package com.lin.manager.secure.filter;

import cn.hutool.core.util.StrUtil;
import com.lin.manager.secure.enums.SecurityEnum;
import com.lin.manager.secure.ex.CustomAccessDeniedException;
import com.lin.manager.secure.handler.CustomSecurityExceptionHandler;
import com.lin.manager.secure.model.SecurityUser;
import com.lin.manager.secure.token.AccessTokenService;
import org.springframework.http.HttpHeaders;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Arrays;
import java.util.regex.Pattern;

/**
 * 作者：lin
 * 功能： jwt身份认证信息 -- 对传入的token进行校验
 * 时间：
 */
public class TokenFilter extends OncePerRequestFilter {

    private static final Pattern AUTHORIZATION_PATTERN = Pattern.compile("^Bearer (?<token>[a-zA-Z0-9-:@#._~+/]+=*)$",
            Pattern.CASE_INSENSITIVE);
    private final AccessDeniedHandler handler = new CustomSecurityExceptionHandler();
    private final PathMatcher pathMatcher = new AntPathMatcher();
    private AccessTokenService accessTokenService;
    private String[] ignoreUrls;


    public void setIgnoreUrls(String[] urls) {
        this.ignoreUrls = urls;
    }

    public void setTokenService(AccessTokenService accessTokenService) {
        this.accessTokenService = accessTokenService;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 地址放行
        boolean match = Arrays.stream(ignoreUrls).anyMatch(url -> pathMatcher.match(url, request.getRequestURI()));
        if (match) {
            filterChain.doFilter(request, response);
            return;
        }

        // 从请求头种获取token数据
        String authorizationToken = request.getHeader(HttpHeaders.AUTHORIZATION);
        if (StringUtils.isEmpty(authorizationToken)) {
            // 防止以往的认证用户还在缓存中
            handler.handle(request, response, new CustomAccessDeniedException(SecurityEnum.LOGIN_FAIL_TOKEN_NULL));
            return;
        }

        String token = authorizationToken.substring(7);
        if (StrUtil.isBlank(token) || !AUTHORIZATION_PATTERN.matcher(authorizationToken).matches()) {
            handler.handle(request, response, new CustomAccessDeniedException(SecurityEnum.LOGIN_FAIL_TOKEN));
            return;
        }

        try {
            // 解析token
            SecurityUser securityUser = accessTokenService.getUserByToken(token);
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(securityUser, null, securityUser.getAuthorities());
            // 将解析出的用户信息放入SecurityContextHodler上下文种
            SecurityContextHolder.getContext().setAuthentication(authentication);
            filterChain.doFilter(request, response);
        } catch (CustomAccessDeniedException ex) {
            handler.handle(request, response, ex);
        }
    }
}
